<?

/* 用法
*$pagesize
*$mysqlpager=new splitResult(pagesize,"page");
*$result=$mysqlpager->page($query,$menudb,true,true); $query为sql语句
*$mysqlpager->currentpage 当前页码
*$mysqlpager->totalnum 总数
*$mysqlpager->nav(true) 页码导航
*/


class splitResult{
	var $currentpage;		//当前页码
	var $nextpage;			//下一页页码
	var $prevpage;			//上一页页码
	var $lasttime;			//当前页码
	var $maxpage;			//最大页码数
	var $time_count;		//统计记录总数
	var $time_query;		//执行SQL所需时间
	var $pagesize;			//每页显示记录数
	var $totalnum;			//总记录数
	var $getpagevar;		//GET参数
	var $initall;			//初始化所有
	var $recount;			//重新统计记录总数
	var $dbresult;			//SQL执行结果
	var $gotopage;			//直接查看页码
	var $gotopage_suffix;	//后辍
	var $forcetotalnum;		//外部指定记录总数
    var $urlrewrite;        //是否使用URL Rewrite
    var $searchreq;         //SQL检索结果数据

	function splitResult($pagesize=20,$pagevar='page',$totalnum=''){  //构造函数，$pagevar 页码参数名称 page=3
		global $_GET,$_POST,$REQUEST_METHOD;	
		
		$this->recount=true; 					//重新统计记录总数
		$this->pagesize=intval($pagesize);
		$this->getpagevar=$pagevar;
		$this->gotopage_suffix="_goto";		
		$this->forcetotalnum=$totalnum;
		//$this->searchreq=$searchreq;


		if ($REQUEST_METHOD=='GET'){	
			$pageinfo=$_GET[$this->getpagevar]; //获取当前页码  值：3
			$this->gotopage=$_GET[$this->getpagevar.$this->gotopage_suffix];  //获取page_goto的值，
		}else{
			$pageinfo=$_POST[$this->getpagevar];
			$this->gotopage=$_POST[$this->getpagevar.$this->gotopage_suffix];		
		}


        if (strlen($pageinfo)<=0){
            $this->initall=true;  	//初始化所有
        }else{
            $tempvar=base64_decode($pageinfo);
            $templist=explode('|',$tempvar); //0:currentpage   1:totalnum   2:time
            if(count($templist)<>3){
                $this->initall=true;					
            }else{
                if (strlen($this->gotopage)>0){
                    $this->currentpage=intval($this->gotopage);	
                    if ($this->currentpage<=0){	$this->currentpage=1;}
                }else{
                    $this->currentpage=intval($templist[0]);  //
                }
                
                $this->totalnum=intval($templist[1]);
                $this->lasttime=intval($templist[2]);
                $this->initall=false;
                if(time()-$this->lasttime<=600){
                    $this->recount=false; //重新统计记录总数
                }								
            }
        }

	}

	function page($sql,$dbh,$auto=true,$recountpertime=false){
		global $_GET;
		if(strlen(trim($sql))<=0){
			die("ERROR:\n<br> file :".__FILE__."  \n<br>line:".__LINE__." \n<br>message: SQL SENTENCE IS NULL.");
		}

		if(strtolower(substr($sql,0,6))!='select'){
			die("ERROR:\n<br> file :".__FILE__."  \n<br>line:".__LINE__." \n<br>message: NON SELECT SENTENCE. \n<br>sql:".$sql);
		}
		
		//去掉Limit
		$sql=preg_replace('/[\t\s]+limit[\t\s]+[0-9]+([\s\t]*\,[\s\t]*[0-9]+)*/i','',$sql);
		//echo $sql."<br>";
		$time1=$this->getmicrotime();
		if($this->initall==true){
			$this->rowsnum($sql,$dbh,$auto);			
			$this->currentpage=1;
			$this->recount=false;
		}else{
			if($this->recount==true or $recountpertime==true){
				$this->rowsnum($sql,$dbh,$auto);		
			}
		}

		$time2=$this->getmicrotime();
		$this->time_count=$time2-$time1;		
		$this->maxpage=ceil($this->totalnum/$this->pagesize);
	

		if ($this->currentpage>$this->maxpage){
			if($this->maxpage>0){
				$this->currentpage=$this->maxpage;
			}else{
				$this->currentpage=1;
			}
		}	
			

		$start=$this->pagesize*($this->currentpage-1);
		$end=$this->pagesize;
		if($this->pagesize*$this->currentpage-$this->totalnum>0){
			$end=$this->pagesize-($this->pagesize*$this->currentpage-$this->totalnum);
		}

 

		$this->prevpage=$this->currentpage-1;
		if($this->prevpage<=0){
			$this->prevpage=1;
		}

		$this->nextpage=$this->currentpage+1;
		if($this->nextpage>=$this->maxpage){
			$this->nextpage=$this->maxpage;
		}

		$newsql=$sql." LIMIT $start,$end ";
		$this->dbresult=mysql_query($newsql,$dbh);
		$time3=$this->getmicrotime();
		$this->time_query=$time3-$time2;
		$_GET[$this->getpagevar]=base64_encode($this->currentpage."|".$this->totalnum."|".$this->lasttime);
		return $this->dbresult;
	}

	//根据$start_page从几页开始显示 Benson
	function page_limit($sql,$dbh,$auto=true,$recountpertime=false,$start_page=1){
		global $_GET;
		
		if(strlen(trim($sql))<=0){
			die("ERROR:\n<br> file :".__FILE__."  \n<br>line:".__LINE__." \n<br>message: SQL SENTENCE IS NULL.");
		}

		if(strtolower(substr($sql,0,6))!='select'){
			die("ERROR:\n<br> file :".__FILE__."  \n<br>line:".__LINE__." \n<br>message: NON SELECT SENTENCE. \n<br>sql:".$sql);
		}
		
		//去掉Limit
		$sql=preg_replace('/[\t\s]+limit[\t\s]+[0-9]+([\s\t]*\,[\s\t]*[0-9]+)*/i','',$sql);
		//echo $sql."<br>";
		$time1=$this->getmicrotime();
		if($this->initall==true){
			$this->rowsnum($sql,$dbh,$auto);			
			$this->currentpage=1;
			$this->recount=false;
		}else{
			if($this->recount==true or $recountpertime==true){
				$this->rowsnum($sql,$dbh,$auto);		
			}
		}

		$time2=$this->getmicrotime();
		$this->time_count=$time2-$time1;		
		$this->maxpage=ceil($this->totalnum/$this->pagesize);
	

		if ($this->currentpage>$this->maxpage){
			if($this->maxpage>0){
				$this->currentpage=$this->maxpage;
			}else{
				$this->currentpage=1;
			}
		}	
			

		$start=$this->pagesize*(($this->currentpage-$start_page)-1);
		$end=$this->pagesize;
		if($this->pagesize*$this->currentpage-$this->totalnum>0){
			$end=$this->pagesize-($this->pagesize*$this->currentpage-$this->totalnum);
		}

 

		$this->prevpage=$this->currentpage-1;
		if($this->prevpage<=0){
			$this->prevpage=1;
		}

		$this->nextpage=$this->currentpage+1;
		if($this->nextpage>=$this->maxpage){
			$this->nextpage=$this->maxpage;
		}

		$newsql=$sql." LIMIT $start,$end ";
		$this->dbresult=mysql_query($newsql,$dbh);
		$time3=$this->getmicrotime();
		$this->time_query=$time3-$time2;
		$_GET[$this->getpagevar]=base64_encode($this->currentpage."|".$this->totalnum."|".$this->lasttime);
		return $this->dbresult;
	}

	/* Memcache Data. Add 2008-10-13  David*/
	function cachepage($sql,$dbh,$mchandle,$cachepage,$timeout=7200){

		global $_GET;
		
		if(strlen(trim($sql))<=0){
			die("ERROR:\n<br> file :".__FILE__."  \n<br>line:".__LINE__." \n<br>message: SQL SENTENCE IS NULL.");
		}

		if(strtolower(substr($sql,0,6))!='select'){
			die("ERROR:\n<br> file :".__FILE__."  \n<br>line:".__LINE__." \n<br>message: NON SELECT SENTENCE. \n<br>sql:".$sql);
		}
		
		//去掉Limit
		$sql=preg_replace('/[\t\s]+limit[\t\s]+[0-9]+([\s\t]*\,[\s\t]*[0-9]+)*/i','',$sql);
		//echo $sql."<br>";

		if($this->initall==true){
			$this->currentpage=1;
			$this->recount=false;
		}

		$mcsid=md5($sql);
		$memresult=$mchandle->get($mcsid);
		if($memresult==false){
			$memresult=array();
			$this->rowsnum($sql,$dbh,$auto);
			if($this->totalnum>0){
				$dbresult=mysql_query($sql." limit 0,".$cachepage*$this->pagesize,$dbh);
				while($row=mysql_fetch_assoc($dbresult)){
					$data[]=$row;
				}
			}
			$memresult['totalnum']=$this->totalnum;
			$memresult['lasttime']=time();
			$memresult['data']=$data;
			$memresult['cachetime']=date('Y-m-d H:i:s');
			$mchandle->set($mcsid,$memresult,false,$timeout);
		}else{
			$this->totalnum=$memresult['totalnum'];
			$this->lasttime=$memresult['lasttime'];
			$data=$memresult['data'];
		}



		$this->maxpage=ceil($this->totalnum/$this->pagesize);

		if ($this->currentpage>$this->maxpage){
			if($this->maxpage>0){
				$this->currentpage=$this->maxpage;
			}else{
				$this->currentpage=1;
			}
		}	
			

		$start=$this->pagesize*($this->currentpage-1);
		$end=$this->pagesize;
		if($this->pagesize*$this->currentpage-$this->totalnum>0){
			$end=$this->pagesize-($this->pagesize*$this->currentpage-$this->totalnum);
		}

 

		$this->prevpage=$this->currentpage-1;
		if($this->prevpage<=0){
			$this->prevpage=1;
		}

		$this->nextpage=$this->currentpage+1;
		if($this->nextpage>=$this->maxpage){
			$this->nextpage=$this->maxpage;
		}



		$_GET[$this->getpagevar]=base64_encode($this->currentpage."|".$this->totalnum."|".$this->lasttime);


		//检查请求的页面是否是缓存内

		if($this->currentpage<=$cachepage){
			for($i=$start;$i<$end+$start;$i++){
				$datalimit[]=$memresult['data'][$i];
			}			
			$memresult['data']=$datalimit;
		}else{
			$newsql=$sql." LIMIT $start,$end ";
			$this->dbresult=mysql_query($newsql,$dbh);
			$datanocache=array();
			while($row=mysql_fetch_assoc($this->dbresult)){
				$datanocache[]=$row;
			}
			$memresult['data']=$datanocache;

		}

		return $memresult;
	}
	
	function nav_en($gobox=false,$language=""){
		if($language=='' || $language=='cn'){
			$this->nav($gobox);
		}else if($language=='en'){
			$this->nav($gobox, array("images"=>1,"showImages"=>true,"showTextLink"=>false,"showCurrentPage"=>true,"showMaxPage"=>true,"language"=>'en'));
		}
	}


    function nav($gobox=false,$navstyle='',$show=true){
        global $_SERVER,$HTTP_HOST,$PHP_SELF,$HTTP_POST_VARS,$_GET;

		$navpicurl="http://$HTTP_HOST";
		$action="http://$HTTP_HOST".$PHP_SELF;

		if($_SERVER['HTTPS']=='on'){
			$navpicurl="https://".$HTTP_HOST;
			$action="https://".$HTTP_HOST.$PHP_SELF;
		}		
		
        if($this->totalnum<=0){
            return false;
        }

		if($this->totalnum>0){
			if(isset($HTTP_POST_VARS)){reset($HTTP_POST_VARS);}
			if(isset($_GET)){reset($_GET);}		
            
			if(is_array($_GET)){
				while(list($index, $value) = each($_GET)) {
					if(strtolower($index)!=$this->getpagevar and strtolower($index)!=$this->getpagevar.$this->gotopage_suffix){
						$tmparray[$index]=$value;
					}
				}
			}

			if(is_array($HTTP_POST_VARS)){  //HTTP_POST_VARS 4.10一下版本，跟$_POST一样
				while(list($index, $value) = each($HTTP_POST_VARS)) {
					if(strtolower($index)!=$this->getpagevar  and strtolower($index)!=$this->getpagevar.$this->gotopage_suffix){
						$tmparray[$index]=$value;
					}
				}
			}
			if(is_array($tmparray)){
				while(list($index, $value) = each($tmparray)) {
					if(strlen($temp)>0){
						$temp.="&";
					}
                    
					if(is_array($value)){
						for($lopp=0;$lopp<count($value);$lopp++){
							$temp.=urlencode($index)."[]=".urlencode($value[$lopp]);
							if($lopp<count($value)-1){$temp.="&";}
						}
					}else{
						$temp.=urlencode($index)."=".urlencode($value);
					}
				}
			}

			//echo $temp;

			if (strlen($temp)>0){
				$temp="?".$temp."&";
			}else{
				$temp="?";
			}
			$temp=str_replace(' ',"%20",$temp);
			$links_first	= base64_encode("1|".$this->totalnum."|".$this->lasttime);
			$links_last		= base64_encode($this->maxpage."|".$this->totalnum."|".$this->lasttime);
			$links_next		= base64_encode($this->nextpage."|".$this->totalnum."|".$this->lasttime);
			$links_prev		= base64_encode($this->prevpage."|".$this->totalnum."|".$this->lasttime);
			$links_this		= base64_encode($this->currentpage."|".$this->totalnum."|".$this->lasttime);

			
			if(is_array($navstyle)==false){
				$navstyle=array(
					"images"=>0,
					"showImages"=>true,
					"showTextLink"=>true,			
					"showCurrentPage"=>true,		
					"showMaxPage"=>true,
					"language"=>'cn'
				);
			}
            
            $navstyle['gobox']=$gobox;
            $navstyle['action']=$action;
            $navstyle['temp']=$temp;
            $navstyle['navpicurl']=$navpicurl;
            $navstyle['links_first']=$links_first;
            $navstyle['links_prev']=$links_prev;
            $navstyle['links_next']=$links_next;
            $navstyle['links_last']=$links_last;
            $navstyle['links_this']=$links_this;
            
            $display_nav_name='display_nav_'.$navstyle['language'];
            if (method_exists($this,$display_nav_name)){
		    	 $buffer=call_user_method($display_nav_name,&$this,$navstyle);
            }else{
                 $buffer=call_user_method('display_nav_en',&$this,$navstyle);
            }

            //die($display_nav_name.":".$buffer);

            if($show){
                echo $buffer;
            }else{
                $data=array(
                    'linkdata'=>$buffer,
                    'links_first'=>$links_first,
                    'links_prev'=>$links_prev,
                    'links_next'=>$links_next,
                    'links_last'=>$links_last,
                    'querystring'=>$temp,
                    'page'=>$this->currentpage,
                    'actionurl'=>$action
                );
                return $data;
            }
		}
	}


function nav2($gobox=false,$navstyle='',$show=true){
        global $_SERVER,$HTTP_HOST,$PHP_SELF,$HTTP_POST_VARS,$_GET;

		$navpicurl="http://$HTTP_HOST";
		$action="http://$HTTP_HOST".$_SERVER['REQUEST_URI'];

		if($_SERVER['HTTPS']=='on'){
			$navpicurl="https://".$HTTP_HOST;
			$action="https://".$HTTP_HOST.$PHP_SELF;
		}		
		
        if($this->totalnum<=0){
            return false;
        }

		if($this->totalnum>0){
			if(isset($HTTP_POST_VARS)){reset($HTTP_POST_VARS);}
			if(isset($_GET)){reset($_GET);}		
            
			if(is_array($_GET)){
				while(list($index, $value) = each($_GET)) {
					if(strtolower($index)!=$this->getpagevar and strtolower($index)!=$this->getpagevar.$this->gotopage_suffix){
						$tmparray[$index]=$value;
					}
				}
			}

			if(is_array($HTTP_POST_VARS)){
				while(list($index, $value) = each($HTTP_POST_VARS)) {
					if(strtolower($index)!=$this->getpagevar  and strtolower($index)!=$this->getpagevar.$this->gotopage_suffix){
						$tmparray[$index]=$value;
					}
				}
			}
			if(is_array($tmparray)){
				while(list($index, $value) = each($tmparray)) {
					if(strlen($temp)>0){
						$temp.="&";
					}
                    
					if(is_array($value)){
						for($lopp=0;$lopp<count($value);$lopp++){
							$temp.=urlencode($index)."[]=".urlencode($value[$lopp]);
							if($lopp<count($value)-1){$temp.="&";}
						}
					}else{
						$temp.=urlencode($index)."=".urlencode($value);
					}
				}
			}

			//echo $temp;

			if (strlen($temp)>0){
				$temp="?".$temp."&";
			}else{
				$temp="?";
			}
			$temp=str_replace(' ',"%20",$temp);
			$links_first	= base64_encode("1|".$this->totalnum."|".$this->lasttime);
			$links_last		= base64_encode($this->maxpage."|".$this->totalnum."|".$this->lasttime);
			$links_next		= base64_encode($this->nextpage."|".$this->totalnum."|".$this->lasttime);
			$links_prev		= base64_encode($this->prevpage."|".$this->totalnum."|".$this->lasttime);
			$links_this		= base64_encode($this->currentpage."|".$this->totalnum."|".$this->lasttime);

			
			if(is_array($navstyle)==false){
				$navstyle=array(
					"images"=>0,
					"showImages"=>true,
					"showTextLink"=>true,			
					"showCurrentPage"=>true,		
					"showMaxPage"=>true,
                                        "hiddenLastLink"=>false,
					"language"=>'cn'
				);
			}
                        
            $navstyle['gobox']=$gobox;
            $navstyle['action']=$action;
            $navstyle['temp']=$temp;
            $navstyle['navpicurl']=$navpicurl;
            $navstyle['links_first']=$links_first;
            $navstyle['links_prev']=$links_prev;
            $navstyle['links_next']=$links_next;
            $navstyle['links_last']=$links_last;
            $navstyle['links_this']=$links_this;
            
            $display_nav_name='display_nav_'.$navstyle['language'];
            if (method_exists($this,$display_nav_name)){
		    	 $buffer=call_user_method($display_nav_name,&$this,$navstyle);
            }else{
                 $buffer=call_user_method('display_nav_en',&$this,$navstyle);
            }

            //die($display_nav_name.":".$buffer);

            if($show){
                echo $buffer;
            }else{
                $data=array(
                    'linkdata'=>$buffer,
                    'links_first'=>$links_first,
                    'links_prev'=>$links_prev,
                    'links_next'=>$links_next,
                    'links_last'=>$links_last,
                    'querystring'=>$temp,
                    'page'=>$this->currentpage,
                    'actionurl'=>$action
                );
                return $data;
            }
		}
	}

   function display_nav_enold($navstyle){
			$buffer='';
			$buffer="<table>\n";
			$buffer.="<tr>\n";


			//需要GoTo表单时
			if($navstyle['gobox']==true){
				$randstr="Form".rand();
				if ($navstyle['temp']=='?'){
					$buffer.="<FORM NAME='".$randstr."' METHOD='POST' ACTION='".$navstyle['action']."'>\n";
				}else{
					$buffer.="<FORM NAME='".$randstr."' METHOD='POST' ACTION='".$navstyle['action'].substr($navstyle['temp'],0,strlen($navstyle['temp'])-1)."'>\n";
				}
			}	
			

			$buffer.="<td align='right'>\n";
			$buffer.="\n";
			
		    //
			if ($navstyle['showCurrentPage'] or $navstyle['showMaxPage']){
				if ($navstyle['showCurrentPage'] and $navstyle['showMaxPage']){
                    $buffer.=" Page " .$this->currentpage." of ". $this->maxpage . " \n";
				}else{
					if($navstyle['showCurrentPage']==false){
                        $buffer.=" Total Page: ". $this->maxpage . " \n";
					}
					
					if($navstyle['showMaxPage']==false){
						$buffer.=" Current Page " .$this->currentpage." \n";			
					}
				}
			}

			if($this->currentpage<=1){
				$buffer.="&nbsp;&nbsp;";
				if($navstyle['showImages']){
					$buffer.="<img src='".$navstyle['navpicurl']."/navimgs/".$navstyle['images']."/first_d.gif' align='absmiddle'>";
				}
				
				if($navstyle['showTextLink']){
                    $buffer.="First";
				}

				$buffer.="&nbsp;&nbsp;";
				if($navstyle['showImages']){
					$buffer.="<img src='".$navstyle['navpicurl']."/navimgs/".$navstyle['images']."/previous_d.gif' align='absmiddle'>";
				}

				if($navstyle['showTextLink']){
					$buffer.="Prev";
				}
			}else{
				$buffer.="&nbsp;&nbsp;<a href=\"" . $navstyle['action'] . $navstyle['temp'] .$this->getpagevar."=".$navstyle['links_first']."\">";

				if($navstyle['showImages']){
					$buffer.="<img src='".$navstyle['navpicurl']."/navimgs/".$navstyle['images']."/first.gif' border='0'  align='absmiddle'>";
				}
				
				if($navstyle['showTextLink']){
					$buffer.="First";
				}


				$buffer.="</a>";


				$buffer.="&nbsp;&nbsp;<a href=\"" . $navstyle['action'] . $navstyle['temp'] .$this->getpagevar. "=" .$navstyle['links_prev'] . "\">";

				if($navstyle['showImages']){
					$buffer.="<img src='".$navstyle['navpicurl']."/navimgs/".$navstyle['images']."/previous.gif' border='0'  align='absmiddle'>";
				}
				
				if($navstyle['showTextLink']){
					$buffer.="Prev";
				}

				$buffer.="</a>";
			}

			if($this->currentpage>=$this->maxpage){
					$buffer.="&nbsp;&nbsp;";
					
					if($navstyle['showTextLink']){
						$buffer.="Next";
					}

					
					if($navstyle['showImages']) {
						$buffer.="<img src='".$navstyle['navpicurl']."/navimgs/".$navstyle['images']."/next_d.gif' border='0' align='absmiddle'>\n";
					}

					$buffer.="&nbsp;&nbsp;";
					if($navstyle['showTextLink']){
						$buffer.="Last";
					}
					
					if($navstyle['showImages']){
						$buffer.="<img src='".$navstyle['navpicurl']."/navimgs/".$navstyle['images']."/last_d.gif' border='0' align='absmiddle'>\n";
					}
			}else{
					$buffer.="&nbsp;&nbsp;<a href=\"" . $navstyle['action'] . $navstyle['temp'] .$this->getpagevar. "=" .$navstyle['links_next'] . "\">";
					
					if($navstyle['showTextLink']){
						$buffer.="Next";
					}

					if($navstyle['showImages']){
						$buffer.="<img src='".$navstyle['navpicurl']."/navimgs/".$navstyle['images']."/next.gif' border='0' align='absmiddle'>";
					}
					
					$buffer.="</a>";

					$buffer.="&nbsp;&nbsp;<a href=\"" . $navstyle['action'] . $navstyle['temp'] .$this->getpagevar. "=" .$navstyle['links_last'] . "\">";

					if($navstyle['showTextLink']){
						$buffer.="Last";
					}

					if($navstyle['showImages']){
						$buffer.="<img src='".$navstyle['navpicurl']."/navimgs/".$navstyle['images']."/last.gif' border='0' align='absmiddle'>";
					}

					$buffer.="</a>";
			}

			
			//显示GOTO表单
			if($navstyle['gobox']==true){			
				if ($navstyle['selectgo']==true){
					$buffer.= "&nbsp; &nbsp; View：<select onChange='".$randstr.".submit();' NAME='".$this->getpagevar.$this->gotopage_suffix."'>";
					for($i=1;$i<=$this->maxpage;$i++){
						$sel=$this->currentpage==$i?" selected":"";
						$buffer.= "<option $sel value='$i'>Page ".$i."</option>\n";
					}
					$buffer.= "</select>\n";
					$buffer.= "<INPUT TYPE='hidden' name='".$this->getpagevar."' value='".$navstyle['links_this']."'>";

				}else{
					$buffer.="&nbsp;&nbsp;Page<INPUT TYPE='text' NAME='".$this->getpagevar.$this->gotopage_suffix."' value='' size='2' style='font-size:7pt'> <INPUT TYPE='submit' value=' Go '  style='font-size:7pt'><INPUT TYPE='hidden' name='".$this->getpagevar."' value='".$navstyle['links_this']."'>";
				}
			}

			$buffer.="</td>\n";


			if($navstyle['gobox']==true){
				$buffer.="</FORM>\n";
			}

			$buffer.="</tr>\n";
			$buffer.="</table>\n";  
            return $buffer;
    }

    function display_nav_cn($navstyle){
			$buffer='';
			$buffer="<table>\n";
			$buffer.="<tr>\n";


			//需要GoTo表单时
			if($navstyle['gobox']==true){
				$randstr="Form".rand();
				if ($navstyle['temp']=='?'){
					$buffer.="<FORM NAME='".$randstr."' METHOD='POST' ACTION='".$navstyle['action']."'>\n";
				}else{
					$buffer.="<FORM NAME='".$randstr."' METHOD='POST' ACTION='".$navstyle['action'].substr($navstyle['temp'],0,strlen($navstyle['temp'])-1)."'>\n";
				}
			}	
			

			$buffer.="<td align='right'>\n";
			$buffer.="\n";
			
		    //
			if ($navstyle['showCurrentPage'] or $navstyle['showMaxPage']){
				if ($navstyle['showCurrentPage'] and $navstyle['showMaxPage']){
					$buffer.=" 第 " .$this->currentpage." 頁/共 ". $this->maxpage . " 頁\n";			
				}else{
					if($navstyle['showCurrentPage']==false){
						$buffer.=" 共 ". $this->maxpage . " 頁\n";						
					}
					
					if($navstyle['showMaxPage']==false){
						$buffer.=" 第 " .$this->currentpage." 頁\n";						
					}
				}
			}

			if($this->currentpage<=1){
				$buffer.="&nbsp;&nbsp;";
				if($navstyle['showImages']){
					$buffer.="<img src='".$navstyle['navpicurl']."/navimgs/".$navstyle['images']."/first_d.gif' align='absmiddle'>";
				}
				
				if($navstyle['showTextLink']){
					$buffer.="首頁";
				}

				$buffer.="&nbsp;&nbsp;";
				if($navstyle['showImages']){
					$buffer.="<img src='".$navstyle['navpicurl']."/navimgs/".$navstyle['images']."/previous_d.gif' align='absmiddle'>";
				}

				if($navstyle['showTextLink']){
					$buffer.="上頁";
				}
			}else{
				$buffer.="&nbsp;&nbsp;<a href=\"" . $navstyle['action'] . $navstyle['temp'] .$this->getpagevar."=".$navstyle['links_first']."\">";

				if($navstyle['showImages']){
					$buffer.="<img src='".$navstyle['navpicurl']."/navimgs/".$navstyle['images']."/first.gif' border='0'  align='absmiddle'>";
				}
				
				if($navstyle['showTextLink']){
					$buffer.="首頁";
				}


				$buffer.="</a>";


				$buffer.="&nbsp;&nbsp;<a href=\"" . $navstyle['action'] . $navstyle['temp'] .$this->getpagevar. "=" .$navstyle['links_prev'] . "\">";

				if($navstyle['showImages']){
					$buffer.="<img src='".$navstyle['navpicurl']."/navimgs/".$navstyle['images']."/previous.gif' border='0'  align='absmiddle'>";
				}
				
				if($navstyle['showTextLink']){
					$buffer.="上頁";
				}

				$buffer.="</a>";
			}

			if($this->currentpage>=$this->maxpage){
					$buffer.="&nbsp;&nbsp;";
					
					if($navstyle['showTextLink']){
						$buffer.="下頁";
					}

					
					if($navstyle['showImages']) {
						$buffer.="<img src='".$navstyle['navpicurl']."/navimgs/".$navstyle['images']."/next_d.gif' border='0' align='absmiddle'>\n";
					}

					$buffer.="&nbsp;&nbsp;";
					if($navstyle['showTextLink']){
						$buffer.="末頁";
					}
					
					if($navstyle['showImages']){
						$buffer.="<img src='".$navstyle['navpicurl']."/navimgs/".$navstyle['images']."/last_d.gif' border='0' align='absmiddle'>\n";
					}
			}else{
					$buffer.="&nbsp;&nbsp;<a href=\"" . $navstyle['action'] . $navstyle['temp'] .$this->getpagevar. "=" .$navstyle['links_next'] . "\">";
					
					if($navstyle['showTextLink']){
						$buffer.="下頁";
					}

					if($navstyle['showImages']){
						$buffer.="<img src='".$navstyle['navpicurl']."/navimgs/".$navstyle['images']."/next.gif' border='0' align='absmiddle'>";
					}
					
					$buffer.="</a>";

					$buffer.="&nbsp;&nbsp;<a href=\"" . $navstyle['action'] . $navstyle['temp'] .$this->getpagevar. "=" .$navstyle['links_last'] . "\">";

					if($navstyle['showTextLink']){
						$buffer.="末頁";
					}

					if($navstyle['showImages']){
						$buffer.="<img src='".$navstyle['navpicurl']."/navimgs/".$navstyle['images']."/last.gif' border='0' align='absmiddle'>";
					}

					$buffer.="</a>";
			}

			
			//显示GOTO表单
			if($navstyle['gobox']==true){			
				if ($navstyle['selectgo']==true){
					$buffer.= "&nbsp; &nbsp; 顯示：<select onChange='".$randstr.".submit();' NAME='".$this->getpagevar.$this->gotopage_suffix."'>";
					for($i=1;$i<=$this->maxpage;$i++){
						$sel=$this->currentpage==$i?" selected":"";
						$buffer.= "<option $sel value='$i'>第".$i."頁</option>\n";
					}
					$buffer.= "</select>\n";
					$buffer.= "<INPUT TYPE='hidden' name='".$this->getpagevar."' value='".$navstyle['links_this']."'>";

				}else{
					$buffer.="&nbsp;&nbsp;第<INPUT TYPE='text' NAME='".$this->getpagevar.$this->gotopage_suffix."' value='' size='2'>頁 <INPUT TYPE='submit' value='查看'><INPUT TYPE='hidden' name='".$this->getpagevar."' value='".$navstyle['links_this']."'>";
				}
			}

			$buffer.="</td>\n";


			if($navstyle['gobox']==true){
				$buffer.="</FORM>\n";
			}

			$buffer.="</tr>\n";
			$buffer.="</table>\n";
            return $buffer;
    
    }
    
     function display_nav_en($navstyle){
        if(!$navstyle['hiddenLastLink']){
            $range=4; 
            $end_val=5;
         }else{
            $range=9;
            $end_val=10;
         }
        $url            = $navstyle['action'];
        $link           = $url.$navstyle['temp'].'page=';
        $totalpage      = $this->maxpage;
        $currentpage    = $this->currentpage;
        $range_start    = $range/2;

        if($totalpage<=9 || $currentpage<=$range_start){
            $start = 1;
        }else{
            $start = ceil($currentpage - $range_start);
        }
            
        if(intval($totalpage)<=9 || intval($totalpage)<$currentpage + $range_start){
            $end = $totalpage;
        }else if($currentpage<9 && $totalpage>9){
            $end = $end_val;
            if($currentpage>=$end_val){
                $end = ceil($currentpage + $range_start);
            }
        }else{
            $end = ceil($currentpage + $range_start);
        }
        
        for( $i = $start; $i <= $end; $i++ ) {
            $page->links    = $link.base64_encode($i."|".$this->totalnum."|".$this->lasttime);
            $page->num      = $i;
            $page->select   = ($currentpage == $i) ? true : false;
            $pages->range[] = $page;
            unset($page);
        }

        
        $pages->firstpageurl    = $link.base64_encode("1|".$this->totalnum."|".$this->lasttime);
		$pages->prepageurl     = $link.base64_encode(intval($currentpage-1)."|".$this->totalnum."|".$this->lasttime);
        $pages->nextpageurl     = $link.base64_encode(intval($currentpage+1)."|".$this->totalnum."|".$this->lasttime);
		$pages->lastpageurl     = $link.base64_encode($totalpage."|".$this->totalnum."|".$this->lasttime);

        $buffer="";
        if( $totalpage > 1 ) {     
             $buffer.="<div class='page_cut'>\n"; 
             $buffer.=" <table border='0' cellspacing='0' cellpadding='0' style='float:right;'>\n";
             $buffer.="     <tr>\n";
             if(!$navstyle['hiddenLastLink']){
                $buffer.="         <td align='right'><span class='page_cur_all'>Page ".$currentpage." of ".$totalpage."</span></td>\n";
             }else{
                $buffer.="         <td align='right'><span class='page_cur_all'></span></td>\n";
             }
			 
			 //返回第一页
             if($currentpage > $start/*(($currentpage + $range_start > $totalpage) && $start > 1) || $pages->range[0]->num > 1  */){ 
                 $buffer.="     <td>\n";
                 $buffer.="         <a href='".$pages->firstpageurl."' class='cur_pageva'>First</a>\n";
                 $buffer.="     </td>\n";
             }else{
				 $buffer.="     <td>\n";
                 $buffer.="         <div class='no_page'>First</div>\n";
                 $buffer.="     </td>\n";
			 }
			 
			 //返回上一页
             if($currentpage > $start){ 
                 $buffer.="     <td>\n";
                 $buffer.="         <a href='".$pages->prepageurl."' class='cur_pageva'>Previous</a>\n";
                 $buffer.="     </td>\n";
             }else{
				 $buffer.="     <td>\n";
                 $buffer.="         <div class='no_page'>Previous</div>\n";
                 $buffer.="     </td>\n";
			 }

             if( $end > 1 ) {
                 foreach($pages->range as $key => $value){
                     if($value->select){
                         $css='class=cur_page';
                     }else{
                         $css='';
                     }
                     $buffer.="                    <td><a href='".$value->links."' ".$css."><strong>".$value->num."</strong></a></td>\n";
                 }
             }else{
                 $buffer.="                    <td align='left'><a class='cur_page' style='cursort:pointer;'>1</a></td>\n";
             }
             
			 //返回下一页
             if($currentpage < $totalpage){
                 $buffer.="            <td>\n";
                 $buffer.="                <a href='".$pages->nextpageurl."' class='cur_pageva'>Next</a> \n";
                 $buffer.="            </td>\n";
             }else{
				 $buffer.="     <td>\n";
                 $buffer.="         <div class='no_page'>Next</div>\n";
                 $buffer.="     </td>\n";
			 }
			 
			 //返回最后一页
             if(!$navstyle['hiddenLastLink']){
                    if($currentpage < $totalpage/*$currentpage + $range_start < $totalpage && $totalpage>9 */){
                        $buffer.="            <td>\n";
                        $buffer.="                <a href='".$pages->lastpageurl."' class='cur_pageva'>Last</a> \n";
                        $buffer.="            </td>\n";
                    }else{
                        $buffer.="     <td>\n";
                        $buffer.="         <div class='no_page'>Last</div>\n";
                        $buffer.="     </td>\n";
                            }
             }
             $buffer.="        </tr>\n";
             $buffer.="    </table>\n";
             $buffer.="</div>\n";
        }    

        return $buffer;
            
    }

	function rowsnum($sql,$dbh,$auto){
		
		//$auto 为true时
		if (strlen($this->forcetotalnum)<=0){
			if($auto==true){
				$tempsql=$this->getcountsql($sql);
				$result=mysql_query($tempsql,$dbh);
				if(!$result){
					die("ERROR:\n<br> file :".__FILE__."  \n<br>line:".__LINE__." \n<br>message: 不能正确识别的SQL查询语句. \n<br>sql:".$tempsql."\n<br>MySQL ERROR: ".mysql_error());			
				}
				
				$rownum=mysql_num_rows($result);		
				if ($rownum>0){
					if(preg_match ("/[\t\s]+group[\t\s]+by[\t\s]+/i",$tempsql)==false){
						$row=mysql_fetch_array($result);
						$this->totalnum=$row[0];
					}else{
						//当SQL用到了分组时,直接用记录数
						$this->totalnum=$rownum;
					}
				}else{
					$this->totalnum=0;				
				}

			}else{
				$result=mysql_query($sql,$dbh);
				$this->totalnum=mysql_num_rows($result);
			}
		}else{
			$this->totalnum=$this->forcetotalnum;
		}
		$this->lasttime=time();		
	}


	function getmicrotime(){ //获取当前时间
		list($usec, $sec) = explode(" ",microtime()); 
		return ((float)$usec + (float)$sec); 
	}

	function getcountsql($sql){
		$sql=trim($sql);
		
		$s=preg_split('/[\s\t]+[fF][rR][oO][mM][\t\s]+/',$sql);
		if (count($s)==2){
			$sql_part1=$s[0];
			$sql_part2=$s[1];

			//去掉order by field_name
			$sql_part2=preg_replace("/order([\s\t]+)by[\t\s]+[a-z0-9_\.]+[\t\s]*(desc|asc)?([\t\s]*\,[\t\s]*[a-z0-9_\.]+[\s\t]*(desc|asc)?)*/i",'',$sql_part2); 

			$sql="SELECT COUNT(".$this->getfirstfield(substr($sql_part1,6)).")  AS totalforpage FROM ".$sql_part2;
		}else{
			die("ERROR:\n<br> file :".__FILE__."  \n<br>line:".__LINE__." \n<br>message: 不能正确识别的SQL查询语句. \n<br>sql:".$sql);			
		}

		//echo $sql;
		return $sql;
		
	}


	function getfirstfield($str){
		$str=trim($str);
		$nofunction=false;
		$s=explode(',',$str);
		$firstfield=trim($s[0]);
		

		//尽可能的避免掉有函数的部分
		for($i=0;$i<count($s);$i++){
			$pos=strrpos($s[$i],'(');
			if($pos==false){
				$firstfield=trim($s[$i]);
				$nofunction=true;
				break;
			}
		}		

		if($nofunction==true){  //无函数的部分时
			//去掉AS语句
			$firstfield=preg_replace('/[\s\t]+[Aa][Ss][\s\t]+/',' ',$firstfield);
			$s=preg_split('/[\s\t]+/',$firstfield);
			$firstfield=$s[0];
		}else{
			//去掉函数  (此部分对复杂的函数会出错，如if,concat,date_format,now 这些多个或无参数MYSQL函数 会出错，请尽量避免在查询语句每一列中用这些函数)
			$pos=strrpos($firstfield,'(');
			$firstfield=substr($firstfield,$pos+1,strpos($firstfield,')')-$pos-1);			
		}


		return trim($firstfield);
		
	}
}

Class splitResultRewrite extends splitResult{
    
    function splitResultRewrite($pagesize=20,$pagevar='page'){

		global $_GET,$_POST,$REQUEST_METHOD;

        $this->recount=false;
		$this->pagesize=intval($pagesize);
		$this->getpagevar=$pagevar;
		$this->gotopage_suffix="_goto";		
		$this->forcetotalnum='';

		if ($REQUEST_METHOD=='GET'){	
			$pageinfo=$_GET[$this->getpagevar];
			$this->gotopage=$_GET[$this->getpagevar.$this->gotopage_suffix];
		}else{
			$pageinfo=$_POST[$this->getpagevar];
			$this->gotopage=$_POST[$this->getpagevar.$this->gotopage_suffix];		
		}

        

        if (strlen($pageinfo)<=0){
            $this->initall=true;
        }else{
            $tempvar=base64_decode($pageinfo);
            $templist=explode('|',$tempvar); //0:currentpage   1:totalnum   2:time
            if(count($templist)<>3){
                $this->initall=true;					
            }else{
                if (strlen($this->gotopage)>0){
                    $this->currentpage=intval($this->gotopage);	
                    if ($this->currentpage<=0){	$this->currentpage=1;}
                }else{
                    $this->currentpage=intval($templist[0]);
                }
                
                $this->totalnum=intval($templist[1]);
                $this->lasttime=intval($templist[2]);
                $this->initall=false;
                if(time()-$this->lasttime<=600){
                    $this->recount=false;
                }								
            }
        }


        /*$this->initall=false;
        $this->recount=false;
        $this->currentpage=intval($pageinfo);
        if ($this->currentpage<=0){	$this->currentpage=1;}
        //$this->totalnum=$searchReq['total'];
        $this->lasttime=time();*/                    
    }

    function nav_rewrite($url,$navstyle='', $is_viewgo = false){
        global $_SERVER;
        $data=$this->nav($is_viewgo,$navstyle,false);
        if($data){
			$_Parameter = '';
            //拆分URL
            if(eregi('(.*)(\.[a-z]+)$',$url,$dd)){
                $url_name=$dd[1].'-';
                $url_ext =$dd[2];   
            }else{
                if(eregi('.+/$',$url)){
                    $url_name=$url;
                }else{
                    $url_name=$url.'/';   
                } 
                $url_ext ='/';
            }            
            if(!empty($_GET)){
                foreach($_GET as $key => $value) {
                    if( $key          == $this->getpagevar)continue;
                    $temp             = '-'.$value;
                }
            }
			
			//其他参数并入
			if($_REQUEST['age1']>0 && $_REQUEST['age2']>0){
				$_Parameter .= $_Parameter==''? '?':'&';
				$_Parameter .= 'age1='.$_REQUEST['age1'].'&age2='.$_REQUEST['age2'];
			}
			if($_REQUEST['sort']!=''){
				$_Parameter .= $_Parameter==''? '?':'&';
				$_Parameter .= 'sort='.$_REQUEST['sort'];
			}
			if($_REQUEST['ssort']!=''){
				$_Parameter .= $_Parameter==''?'?':'&';
				$_Parameter .= 'ssort='.$_REQUEST['ssort'];
			}
			
            $urlcomm_old=$data['actionurl'].$data['querystring'].$this->getpagevar.'=';
            //替换首页
            $list='p-'.$data['links_first'];
            $linkurl_old=$urlcomm_old.$data['links_first'];
            $linkurl_new=$url_name.$ssid.$list.$temp.'.html'.$_Parameter;
            $data['linkdata']=str_replace($linkurl_old,$linkurl_new,$data['linkdata']);

            //替换上一页
            $list='p-'.$data['links_prev'];
            $linkurl_old=$urlcomm_old.$data['links_prev'];
            $linkurl_new=$url_name.$ssid.$list.$temp.'.html'.$_Parameter;
            $data['linkdata']=str_replace($linkurl_old,$linkurl_new,$data['linkdata']);

            //替换下一页
            $list='p-'.$data['links_next'];
            $linkurl_old=$urlcomm_old.$data['links_next'];
            $linkurl_new=$url_name.$ssid.$list.$temp.'.html'.$_Parameter;
            $data['linkdata']=str_replace($linkurl_old,$linkurl_new,$data['linkdata']);

            //替换末页
            if(!$navstyle['hiddenLastLink']){
                $list='p-'.$data['links_last'];
                $linkurl_old=$urlcomm_old.$data['links_last'];
                $linkurl_new=$url_name.$ssid.$list.$temp.'.html'.$_Parameter;
                $data['linkdata']=str_replace($linkurl_old,$linkurl_new,$data['linkdata']);
            }
            //echo str_replace($_SERVER['PHP_SELF'],$url,$data['linkdata']);
            echo $data['linkdata'];
        }
    }
	
    
}
?>